package org.devf.fork.imsimulator.socket;

import java.io.IOException;
import java.net.Socket;

/**
 * DefaultTcpServer related
 *
 * @author wanghuafu
 * @since 1.0  2023/9/12 14:34
 */
public class DefaultTcpClient implements TcpClient {

    private final String host;
    private final Integer port;
    private Socket socket;
    private boolean hadDestroy;

    public DefaultTcpClient(String host, Integer port) {
        this.host = host;
        this.port = port;
    }

    @Override
    public boolean create() {
        try {
            if (null != socket && !socket.isClosed() && !socket.isConnected()) {
                return true;
            }
            socket = new Socket(host, port);
            SocketConfig.init();

            // 创建一个线程用于接收消息
            Thread receiveThread = new Thread(new ReceiveRunnable(socket.getInputStream(),this.getChannel()));
            receiveThread.start();

            //程序推出后关掉socket
            Runtime.getRuntime().addShutdownHook(new Thread(this::destroy));
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }


    @Override
    public void destroy() {
        System.out.println("socket关闭...");
        if (socket!=null) {
            try {
                hadDestroy = true;
                SocketConfig.isStopRead = true;
                socket.close();//日志？
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public Channel getChannel() {
        // 获取输出流（用于发送消息）
        try {
            return new TcpWriteChannel(this.socket.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    public boolean isHadDestroy() {
        return hadDestroy;
    }
}
